#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
    struct Data {
        int start, size;
        Data(int start_, int size_):start(start_), size(size_) {

        }
    };


public:
    string arrangeWords(string text) {
        vector<Data> datas;
        int start = 0;
        while (start < text.size()) {
            int end = start + 1;
            while (end < text.size() && text[end] != ' ')++end;
            datas.emplace_back(start, end- start);
            start = end + 1;
        }
        sort(datas.begin(), datas.end(), [](const Data& left, const Data& right) {
            return left.size < right.size || (left.size == right.size && left.start < right.start);
            });
        string res = "";
        for (int i = 0; i < datas.size(); ++i) {
            auto str = text.substr(datas[i].start, datas[i].size);
            if (i == 0) {
                if (str[0] >= 'a' && str[0] <= 'z') {
                    str[0] = str[0] - 'a' + 'A';
                }
            }
            else if (datas[i].start == 0) {
                str[0] = str[0] - 'A' + 'a';
            }
            if (i + 1 < datas.size())
                str += ' ';
            res += str;
        }
        return res;
    }
};